//
//  commDetailCell.m
//  yunbaolive
//
//  Created by Boom on 2018/12/17.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "commDetailCell.h"
#import "YBCenterVC.h"
@implementation commDetailCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.contentView.backgroundColor = [UIColor clearColor];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _iconIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 2, 22, 22)];
        _iconIV.layer.masksToBounds = YES;
        _iconIV.layer.cornerRadius = 12;
        [self.contentView addSubview:_iconIV];
        
        //_nameL = [[UILabel alloc]initWithFrame:CGRectMake(_iconIV.right+2, 3, self.contentView.width, 20)];
        _nameL = [[UILabel alloc]init];
        _nameL.textColor = RGB_COLOR(@"#969696", 1);
        _nameL.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:_nameL];
        [_nameL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_iconIV);
            make.left.equalTo(_iconIV.mas_right).offset(2);
        }];
        
        //_authorL = [[UILabel alloc]initWithFrame:CGRectMake(_nameL.right+5, 5, 24, 14)];
        _authorL = [[UILabel alloc]init];
        _authorL.textColor = [UIColor whiteColor];
        _authorL.font = [UIFont systemFontOfSize:10];
        _authorL.backgroundColor = RGB_COLOR(@"#ff0066", 1);//Pink_Cor;
        _authorL.textAlignment = NSTextAlignmentCenter;
        _authorL.layer.masksToBounds = YES;
        _authorL.layer.cornerRadius = 3;
        _authorL.text = YZMsg(@"作者");
        [self.contentView addSubview:_authorL];
        [_authorL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_iconIV);
            make.left.equalTo(_nameL.mas_right).offset(5);
            make.width.equalTo(@24);
            make.height.equalTo(@14);
        }];
        
        _zanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _zanBtn.frame = CGRectMake(_window_width-45-15-30, 0, 30, 30);
        _zanBtn.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        [_zanBtn addTarget:self action:@selector(clickReplayZanBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_zanBtn];
        
        _zanL = [[UILabel alloc]initWithFrame:CGRectMake(_zanBtn.left-10, _zanBtn.bottom, 50, 15)];
        _zanL.textAlignment = NSTextAlignmentCenter;
        _zanL.font = SYS_Font(11);
        [self.contentView addSubview:_zanL];
        
        _contentL = [[YYLabel alloc]init];
        _contentL.textColor =UIColor.blackColor;
        _contentL.font = [UIFont systemFontOfSize:14];
        _contentL.numberOfLines = 0;
        self.contentView.backgroundColor = UIColor.whiteColor;
        [self.contentView addSubview:_contentL];

        _voiceView = [[UIView alloc]init];
        _voiceView.hidden = YES;
        [self.contentView addSubview:_voiceView];
        [_voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_nameL.mas_left);
            make.top.equalTo(_nameL.mas_bottom).offset(2);
            make.width.mas_equalTo(70);
            make.height.mas_equalTo(20);
        }];
        UIButton *playBtn = [UIButton buttonWithType:0];
        [playBtn setImage:[UIImage imageNamed:@"commen-yuyin"] forState:0];
        [playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_voiceView addSubview:playBtn];
        [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.width.height.equalTo(_voiceView);
        }];
        
        _voiceNorImgV = [[UIImageView alloc]init];
        _voiceNorImgV.image = [UIImage imageNamed:@"comment_voice_nor"];
        [_voiceView addSubview:_voiceNorImgV];
        [_voiceNorImgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_voiceView);
            make.left.equalTo(_voiceView).offset(8);
            make.width.height.mas_equalTo(7);
        }];
        
        _voiceTimeL = [[UILabel alloc]init];
        _voiceTimeL.textColor = [UIColor whiteColor];
        _voiceTimeL.font = [UIFont systemFontOfSize:8];
        [_voiceView addSubview:_voiceTimeL];
        [_voiceTimeL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_voiceView);
            make.right.equalTo(_voiceView).offset(-4);
        }];
        
        _animationView = [[YYAnimatedImageView alloc]init];
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"voice_pinglun" withExtension:@"gif"];
        _animationView.yy_imageURL = url;
        _animationView.hidden = YES;
        [_voiceView addSubview:_animationView];
        [_animationView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_voiceView);
            make.width.mas_equalTo(13);
            make.height.mas_equalTo(10);
        }];
        
        _longPressView = [[UIView alloc]init];
        [self.contentView addSubview:_longPressView];
        [self.contentView sendSubviewToBack:_longPressView];
        [_longPressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_iconIV.mas_top).offset(-5);
            make.left.equalTo(_iconIV.mas_left).offset(-5);
            make.right.equalTo(_zanBtn.mas_right).offset(5);
            make.bottom.equalTo(_contentL.mas_bottom).offset(3);
        }];
        
        
        UIButton *iconShadowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [iconShadowBtn addTarget:self action:@selector(clickIconBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:iconShadowBtn];
        [iconShadowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.equalTo(_iconIV);
            make.width.equalTo(_iconIV.mas_width).offset(10);
            make.height.equalTo(_iconIV.mas_height).offset(10);
        }];

    }
    return self;
}
- (void)playBtnClick:(UIButton *)sender{
    [self.delegate playVoice:_model andCell:self];
}
-(void)setAuthorID:(NSString *)authorID {
    _authorID = authorID;
}
- (void)setModel:(detailmodel *)model{
    _model = model;
    _authorL.hidden = YES;
    if ([_authorID isEqual:_model.ID]) {
        _authorL.hidden = NO;
    }
    if ([model.isvoice isEqual:@"1"]) {
        _voiceView.hidden = NO;
        _voiceView.height = NO;
        _animationView.hidden = YES;
        _voiceTimeL.text = [NSString stringWithFormat:@"%@\"",model.voiceTime];
    }else{
        _voiceView.hidden = YES;
    }
    [_iconIV sd_setImageWithURL:[NSURL URLWithString:_model.avatar_thumb]];
    _nameL.text = _model.user_nickname;
    
    if ([_model.islike isEqual:@"1"]) {
        [_zanBtn setImage:[UIImage imageNamed:@"likecomment-click"] forState:0];
        _zanL.textColor = Pink_Cor;
    }else{
        [_zanBtn setImage:[UIImage imageNamed:@"likecomment"] forState:0];
        _zanL.textColor = RGB_COLOR(@"#828282", 1);
    }
    _zanL.text = _model.likes;
    
    _contentL.frame = _model.contentRect;
    NSArray *resultArr  = [PublicObj machesWithPattern:emojiPattern andStr:_model.content];
    if (!resultArr) return;
    NSUInteger lengthDetail = 0;
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:_model.content];
    //遍历所有的result 取出range
    for (NSTextCheckingResult *result in resultArr) {
        //取出图片名
        NSString *imageName =   [_model.content substringWithRange:NSMakeRange(result.range.location, result.range.length)];
        if ([lagType isEqual:EN]) {
            if ([imageName isEqual:@"[互粉]"] ||
                [imageName isEqual:@"[关注]"] ||
                [imageName isEqual:@"[粉]"] ||
                [imageName isEqual:@"[给力]"]) {
                imageName = [imageName stringByAppendingFormat:@"_en"];
            }
        }
        NSLog(@"--------%@",imageName);
        NSTextAttachment *attach = [[NSTextAttachment alloc] init];
        UIImage *emojiImage = [UIImage imageNamed:imageName];
        NSAttributedString *imageString;
        if (emojiImage) {
            /*
            attach.image = emojiImage;
            attach.bounds = CGRectMake(0, -2, 15, 15);
            imageString =   [NSAttributedString attributedStringWithAttachment:attach];
            */
            UIImageView *imageV = [[UIImageView alloc] init];
            imageV.frame = CGRectMake(0, -2, 15, 15);
            imageV.image = emojiImage;
            imageString = [NSAttributedString yy_attachmentStringWithContent:imageV contentMode:UIViewContentModeScaleAspectFit attachmentSize:CGSizeMake(15, 15) alignToFont:_contentL.font alignment:YYTextVerticalAlignmentCenter];
        }else{
            imageString =   [[NSMutableAttributedString alloc]initWithString:imageName];
        }
        //图片附件的文本长度是1
        NSLog(@"emoj===%zd===size-w:%f==size-h:%f",imageString.length,imageString.size.width,imageString.size.height);
        NSUInteger length = attStr.length;
        NSRange newRange = NSMakeRange(result.range.location - lengthDetail, result.range.length);
        [attStr replaceCharactersInRange:newRange withAttributedString:imageString];
        
        lengthDetail += length - attStr.length;
    }
    NSAttributedString *dateStr = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@" %@",_model.datetime] attributes:@{NSForegroundColorAttributeName:RGB_COLOR(@"#969696", 1),NSFontAttributeName:[UIFont systemFontOfSize:12]}];
    [attStr appendAttributedString:dateStr];
    //不同字体居中对齐、基线偏移比率
    [attStr addAttribute:NSBaselineOffsetAttributeName value:@(0.36 * (14 - 11)) range:NSMakeRange(attStr.length - _model.datetime.length, _model.datetime.length)];
    [attStr addAttribute:NSForegroundColorAttributeName value:UIColor.blackColor range:attStr.yy_rangeOfAll];//RGB_COLOR(@"#FFFFFF", 1)

    //给被@加颜色
    NSData *mix_data = [_model.at_info dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *atArray = [NSJSONSerialization JSONObjectWithData:mix_data options:NSJSONReadingAllowFragments error:nil];
    if (atArray.count>0) {
        //有@
        for (int i=0; i<atArray.count; i++) {
            NSDictionary *u_dic = atArray[i];
            NSString *uname = [NSString stringWithFormat:@"@%@",[u_dic valueForKey:@"name"]];
            if ([_model.content containsString:uname]) {
                NSRange uRang = [_model.content rangeOfString:uname];
//                [attStr addAttribute:NSForegroundColorAttributeName value:AtCol range:uRang];
                [attStr yy_setTextHighlightRange:uRang color:AtCol backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                    NSLog(@"回复进入个人中心");
                    YBCenterVC *center = [[YBCenterVC alloc]init];
                    center.otherUid = minstr([u_dic valueForKey:@"uid"]);
                    center.isPush = YES;
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
                    if (self.delegate && [self.delegate respondsToSelector:@selector(endEnterCenter)]) {
                        [self.delegate endEnterCenter];
                    }

                }];

            }
        }
    }
    if ([_model.touid intValue]>0) {
        NSRange repeatRange = [[attStr string]rangeOfString:[NSString stringWithFormat:@"%@:",[_model.touserinfo valueForKey:@"user_nickname"]]];
        [attStr addAttributes:@{NSForegroundColorAttributeName:RGB_COLOR(@"#969696", 1)} range:repeatRange];
    }
    
    //更新到label上
    _contentL.attributedText = attStr;

}
-(void)clickReplayZanBtn {
    if ([[Config getOwnID] intValue]<=0 && _delegate && [_delegate respondsToSelector:@selector(warningLogin)]) {
        //[PublicObj warnLogin];
        [_delegate warningLogin];
        return;
    }
    
    if ([_model.ID isEqual:[Config getOwnID]]) {
        [MBProgressHUD showError:YZMsg(@"不能给自己的评论点赞")];
        return;
    }

    NSString *url = [NSString stringWithFormat:@"Video.addCommentLike&uid=%@&commentid=%@&token=%@",[Config getOwnID],_model.parentid,[Config getOwnToken]];
    
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            //动画
            dispatch_async(dispatch_get_main_queue(), ^{
                [_zanBtn.imageView.layer addAnimation:[PublicObj bigToSmallRecovery] forKey:nil];
            });
            
            NSDictionary *infoDic = [info firstObject];
            NSString *islike = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"islike"]];
            NSString *likes = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"likes"]];
            _zanL.text = likes;
            if ([islike isEqual:@"1"]) {
                [_zanBtn setImage:[UIImage imageNamed:@"likecomment-click"] forState:0];
                _zanL.textColor = Pink_Cor;
            }else{
                [_zanBtn setImage:[UIImage imageNamed:@"likecomment"] forState:0];
                _zanL.textColor = RGB_COLOR(@"#828282", 1);
            }
            if ([_delegate respondsToSelector:@selector(refreshDtailDataWithId:andLikes:islike:)]) {
                [_delegate refreshDtailDataWithId:_model.parentid andLikes:likes islike:islike];
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        
    }];
    
}

-(void)clickIconBtn {
    if ([[Config getOwnID] intValue]<=0 && _delegate && [_delegate respondsToSelector:@selector(warningLogin)]) {
        [_delegate warningLogin];
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(endEditOfGoHome)]) {
        [self.delegate endEditOfGoHome];
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"goCenterNot" object:@"1"];
    YBCenterVC *center = [[YBCenterVC alloc]init];
    center.otherUid = _model.ID;
    center.isPush = YES;
    center.hidesBottomBarWhenPushed = YES;
    center.backEvent = ^{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"goCenterNot" object:@"0"];
    };
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
    
    
}
@end
